package com.wang.cloud.common.mysql.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源-config-dmeo
 *
 * @author wang ye
 * @date 2024/6/27
 */
@Configuration
public class DateSourceConfig {


    @Bean
    @ConfigurationProperties("spring.datasource.druid.datasource1")
    public DataSource dynamicDatasource1() {
        return DruidDataSourceBuilder.create()
                .build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.datasource2")
    public DataSource dynamicDatasource2() {
        return DruidDataSourceBuilder.create()
                .build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.datasource3")
    public DataSource dynamicDatasource3() {
        return DruidDataSourceBuilder.create()
                .build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource createDynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>();
        // 设置默认的数据源为Master
        DataSource dynamicDatasource1 = dynamicDatasource1();
        DataSource dynamicDatasource2 = dynamicDatasource2();
        DataSource dynamicDatasource3 = dynamicDatasource3();
        dataSourceMap.put("db1", dynamicDatasource1);
        dataSourceMap.put("db2", dynamicDatasource2);
        dataSourceMap.put("db3", dynamicDatasource3);
        return new DynamicDataSource(dynamicDatasource1, dataSourceMap);
    }

}
